<style scoped>
.mask{
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: #000;
    opacity: 0.3;
    z-index: 9;
}
._ReviSion{
    position: fixed;
    top: 15%;
    left: 50%;
    transform: translateX(-50%);
    width: 1240px;
    z-index: 99;
    background-color: white;
    overflow: auto;
}
.RS_top{
    height: 40px;
    background: #f8f8f8;
    display: flex;
    justify-content: space-between;
    padding: 10px 15px;
}
.RS_top p{
    font-weight: 700;
}
.RS_middle{
    width: 1210px;
    /* border: 1px solid black; */
    margin: 10px 15px;
}
.button_box{
    background: #f8f8f8;
    width: 100%;
    height: 60px;
    padding: 15px 0;
    display: flex;
}
.inp_box2{
    background: #f8f8f8;
    width: 100%;
    height: 60px;
    padding: 15px 0;
    margin: 15px 0;
    display: flex;
}
.inp_box{
    display: flex;
    margin: 15px 0 10px 0;
}
._ReviSion input:focus{
    outline: none;
    border: 1px solid #2a8ffc;
  }
  .inp{
    border: 1px solid #dbdbdb;
    border-radius: 3px;
    height: 30px;
    padding: 0 15px;
  }
  .inp2{
    width: 160px;
  }
  .inp3{
    width: 60px;
    margin-right: 10px;
  }
  .inp4{
      width: 400px;
  }
  .inp5{
      width: 160px;
  }
  .inp6{
      width: 125px;
  }
  .RS_button{
      margin-left: 1070px;
  }

  ._ReviSion .inp_box p, ._ReviSion .inp_box2 p{
    display: inline-block;
    width: 75px;
    line-height: 30px;
    text-align: right;
    margin-right: 5px;
  }
</style>

<style>
.SReviSion ._ReviSion .inp_box .el-input__inner {
    height: 30px!important;
    width: 160px;
}
.SReviSion ._ReviSion .inp_box .sty .el-input__inner {
    height: 30px;
    width: 90px;
}
.SReviSion ._ReviSion .inp_box .sty2 .el-input__inner {
    height: 30px;
    width: 80px;
}
.SReviSion ._ReviSion .inp_box .sty3 .el-input__inner {
    height: 30px;
    width: 160px;
}
.SReviSion ._ReviSion .RS_middle .inp_box2 .el-input__inner {
    height: 30px;
    width: 160px;
}
.SReviSion ._ReviSion .el-checkbox.is-bordered{
    height: 30px;
    padding: 4px 8px 0;
    margin: 0 0 0 10px;
}
.SReviSion ._ReviSion .el-checkbox__inner{
    border-radius: 50%;
}

</style>

<template>
  <div class="SReviSion">
    <div class="mask"></div>
    <div class="_ReviSion">
      <div class="RS_top">
        <p>改单(客户销货查询)</p>
        <i @click="closeReviSion" class="el-icon-close"></i>
      </div>
      <div class="RS_middle">
        <div class="button_box">
          <el-button @click="search" type="primary" icon="el-icon-search">查询</el-button>
          <el-button @click="modification()" icon="el-icon-edit-outline">修改</el-button>
        </div>
        <div class="inp_box">
          <p>销货日期</p>
          <el-date-picker class="inp2" v-model="inputDate" type="date" value-format="yyyy-MM-dd" placeholder="选择日期" :disabled="changeNo"></el-date-picker>
          <p>客户编号</p>
          <input class="inp inp3" type="text" v-model="customerNo" @blur="customerNoBlur" :disabled="lockNo || jxAgent || isAffirm">
          <div class="sty">
            <el-select v-model="customerName" @change="customerChange" :disabled="lockNo || jxAgent || isAffirm">
              <el-option v-for="item in customerL" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </div>
          <p>单号</p>
          <input class="inp inp2" type="text" v-model="receiptsNumber" disabled>
          <p>销货序号</p>
          <input class="inp inp2" type="text" v-model="sequence" disabled>
          <p>货号</p>
          <input class="inp inp2" type="text" v-model="kindsNumber" disabled></div>
        <div class="inp_box">
          <p>客户简称</p>
          <input class="inp inp2" type="text" v-model="customerName" disabled>
          <p>折数</p>
          <input class="inp inp5" type="text" v-model="discount" style="width:80px" :disabled="!checked1" @blur="discountBlur">
          <el-checkbox v-model="checked1" border label="改动" key="saleCheck1" :disabled="changeNo"></el-checkbox>
          <p>配货方式</p>
          <div class="sty2">
            <el-select v-model="cooperateWay" :disabled="changeNo">
              <el-option v-for="item in cooperateWayList" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </div>
          <el-checkbox v-model="checked2" border label="返现" key="saleCheck2" :disabled="changeNo"></el-checkbox>
          <p>实收单价</p>
          <input class="inp inp6" type="text" v-model="actualPrice" style="width:80px" :disabled="!checked3" @blur="actualPriceBlur">
          <el-checkbox v-model="checked3" border label="选择" key="saleCheck3" :disabled="changeNo"></el-checkbox>
          <p>数量</p>
          <input class="inp inp2" type="text" v-model="sum" @blur="sumBlur" :disabled="changeNo"></div>
        <div class="inp_box">
          <p>备注</p>
          <input type="text" class="inp inp4" v-model="remark" :disabled="changeNo"></div>
        <div class="inp_box2">
          <p>货号</p>
          <div class="sty3">
            <el-input v-model="searchKindsNumber"></el-input>
          </div>
          <p>销货序号</p>
          <el-input style="width:160px;" v-model="searchInputSequence"></el-input>
        </div>
        <el-table height="250" :data="tableData" 
          highlight-current-row 
          style="width: 100%" 
          :header-cell-style="{background:'#f4f4f4',padding:0,height:'40px'}" 
          :cell-style="{padding:0,height:'36px'}"
           @row-click="rowClick">
          <el-table-column type="index" label="序号" width="50"></el-table-column>
          <el-table-column property="sequence" label="销货序号" width="120"></el-table-column>
          <el-table-column property="no" label="客户编号" width="80"></el-table-column>
          <el-table-column property="receiptsNumber" label="单据号" width="140"></el-table-column>
          <el-table-column property="kindsNumber" label="货号" min-width="160"></el-table-column>
          <el-table-column property="colorNameNo" label="色码" width="80"></el-table-column>
          <el-table-column property="sizeNo" label="尺码编码" width="80"></el-table-column>
          <el-table-column property="sellingPrice" label="售价"></el-table-column>
          <el-table-column property="discount" label="折数" width="50">
            <template slot-scope="scope">
              <el-input size="small" 
                class="minipadInp"
                v-model="scope.row.discount" 
                @blur="itemDiscount(scope.row)">
              </el-input>
            </template>
          </el-table-column>
          <el-table-column property="onePrice" label="单价"></el-table-column>
          <el-table-column property="money" label="金额"></el-table-column>
          <el-table-column property="time" label="销货日期" width="100"></el-table-column>
          <el-table-column property="entryTime" label="录入日期" width="160"></el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script>
import { updateReceipt, getSellInquire, affirmUpdateReceipt, maxSellTime, updateByAffirm, settleAccountsStatus } from '../../../../network/sellTotal'

export default {
  props: {
    selectInputSequence: {
      type: String,
      default: ''
    },
    customerL: {
      type: Array,
      default: []
    },
    flag: {
      type: Boolean,
      default: false
    },
    detailRow: {
      type: Object,
      default: {}
    },
    Str: {
      type: String,
      default: ''
    }
  },
  data(){
    return{
      updateData: {},
      inputDate: null,
      customerNo: '',
      customerName: '',
      receiptsNumber: '',
      sequence: '',
      kindsNumber: '',
      discount: '',
      cooperateWay: '',
      cooperateWayList: [
        {value:'配货',label:'配货'},
        {value:'订货',label:'订货'},
        {value:'订断',label:'订断'},
        {value:'追断',label:'追断'}
      ],
      actualPrice: '',
      sum: '',
      remark: '',
      searchKindsNumber: '',
      searchInputSequence: '',
      checked1: false,
      checked2: false,
      checked3: false,
      isAffirm: false,
      changeNo: false,
      lockNo: false,

      sellingPrice: '',
      updateData: {},

      tableData: [],
      jxAgent: document.cookie.match(RegExp('jxAgent'+'=([^;]+)'))[1] == 1 ? true : false,

      settleAccount: null
    }
  },
  watch: {
    flag(a,b){
      if (a) {
        if (JSON.stringify(this.detailRow) == "{}") {
          this.search()
        } else {
          this.searchKindsNumber = this.detailRow.kindsNumber
          // this.detailRow.sellTime += ' 12:00:00'
          this.tableData = [this.detailRow]
          this.fillBlanks(this.detailRow)
          this.rowClick(this.detailRow)
        }
      }
    },
    selectInputSequence(a,b){
      if (a) {
        this.searchInputSequence = a
        this.sequence = a
      }
    },
    checked1(a,b){
      if (a && !this.lockNo) {
        this.lockNo = true
      }
    },
    checked2(a,b){
      if (a && !this.lockNo) {
        this.lockNo = true
      }
      this.updateData.isReturn = a ? 1 : 0
    },
    checked3(a,b){
      if (a && !this.lockNo) {
        this.lockNo = true
      }
    },
    // receiptsNumber(a,b){
    //   this.receiptsNumber = a.toUpperCase().trim()
    //   if (this.tableData.length && a != this.tableData[0].receiptsNumber && !this.lockNo) {
    //     this.lockNo = true
    //   }
    //   this.tableData.forEach(e => {
    //     e.receiptsNumber = a
    //   })
    //   this.$forceUpdate()
    // },
    inputDate(a,b){
      if (this.tableData.length && a != this.tableData[0].sellTime && !this.lockNo) {
        this.lockNo = true
      }
      this.tableData.forEach(e => {
        e.sellTime = a
        e.time = a.slice(0,10)
      })
    },
    cooperateWay(a,b){
      if (this.tableData.length && a != this.tableData[0].cooperateWay && !this.lockNo) {
        this.lockNo = true
      }
      this.tableData.forEach(e => {
        e.cooperateWay = a
      })
    },
    remark(a,b){
      if (this.tableData.length && a != this.tableData[0].remark && !this.lockNo) {
        this.lockNo = true
      }
      this.tableData.forEach(e => {
        e.remark = a
      })
    },
    customerNo(a,b){
      this.customerNo = a.toUpperCase().trim()
    },
    searchKindsNumber(a,b){
      this.searchKindsNumber = a.toUpperCase().trim()
    },
    searchInputSequence(a,b){
      this.searchInputSequence = a.toUpperCase().trim()
    }
  },
  methods:{
    checkDate(){
      // return
      maxSellTime({customerNo: this.customerNo}).then(res => {
        this.maxSellDate = res.data.data ? res.data.data.slice(0,10) : this.inputDate
        if (this.judgeTime(this.inputDate.slice(0,10),this.maxSellDate)) {
          this.$message.info('时间不合法，不能早于' + this.maxSellDate)
        }
        console.log(this.maxSellDate)
      })
    },
    // 判断时间先后
    judgeTime(a,b){
      // console.log(a,b)
      // console.log(Number(a.replace(/-/g,'')))
      // console.log(Number(b.replace(/-/g,'')))
      if (Number(a.replace(/-/g,'')) >= Number(b.replace(/-/g,''))) {
        return false
      } else {
        return true
      }
    },
    clearData(){
      this.inputDate = null
      this.customerNo = ''
      this.customerName = ''
      this.receiptsNumber = ''
      this.sequence = ''
      this.kindsNumber = ''
      this.discount = ''
      this.cooperateWay = ''
      this.checked1 = false
      this.checked2 = false
      this.checked3 = false
      this.actualPrice = ''
      this.sum = ''
      this.remark = ''
      this.tableData = []
      this.lockNo = false
      this.changeNo = false
    },
    
    closeReviSion(){
      this.$emit('closeReviSion')
      this.clearData()
      this.searchKindsNumber = ''
      this.searchInputSequence = ''
    },

    // 客户编号失去焦点
    customerNoBlur(){
      if (this.customerNo) {
        for (const i of this.customerL) {
          if (this.customerNo == i.value) {
            this.customerName = i.label
            this.checkDate()
            if (this.tableData.length && this.customerNo != this.tableData[0].no) {
              this.changeNo = true
              this.tableData.forEach(e => {
                e.no = this.customerNo
                e.name = i.label
              })
            }
            return
          }
        }
        this.$message.error('无此客户编号')
        this.customerNo = this.tableData[0].no
        this.customerNoBlur()
      } else {
        this.customerName = this.tableData[0].no
      }
    },

    discountBlur(){
      let a = this.discount
      let r = /^\d(\.\d)?$|^10$/
      if (!r.test(a)) {
        this.$alert('折数请输入10以内数字，小数不得超过一位', '', {
          confirmButtonText: '确定'
        })
        this.discount = this.updateData.discount
        return
      }
      if (this.tableData.length && a != this.tableData[0].discount && !this.lockNo) {
        this.lockNo = true
      }
      this.tableData.forEach(e => {
        e.discount = a
        e.onePrice = (e.sellingPrice * a / 10).toFixed(2)
        e.money = (e.onePrice * e.sum).toFixed(2)
        e.updateMoney = (e.money - e.initialMoney).toFixed(2)
      })
      // this.updateData.discount = a
      // this.updateData.onePrice = (this.updateData.sellingPrice * a / 10).toFixed(2)
      // this.updateData.money = (this.updateData.onePrice * this.updateData.sum).toFixed(2)
      // this.updateData.updateMoney = (this.updateData.money - this.updateData.initialMoney).toFixed(2)
    },
    actualPriceBlur(){
      let a = this.actualPrice
      let r = /^[1-9]\d*(.[0-9]{1,2})?$/
      if (!r.test(a)) {
        this.$alert('实收单价请输入数字，小数不得超过两位', '', {
          confirmButtonText: '确定'
        })
        this.actualPrice = this.updateData.onePrice
        return
      }
      if (this.tableData.length && a != this.tableData[0].onePrice && !this.lockNo) {
        this.lockNo = true
      }
      this.updateData.onePrice = a
      this.discount = (a / this.updateData.sellingPrice * 10).toFixed(1)
      this.updateData.discount = this.discount
      this.updateData.money = (this.updateData.onePrice * this.updateData.sum).toFixed(2)
      this.updateData.updateMoney = (this.updateData.money - this.updateData.initialMoney).toFixed(2)
    },
    sumBlur(){
      let a = this.sum
      let r = /^(0|[1-9]\d*)$/
      if (!r.test(a)) {
        this.$alert('数量请输入整数', '', {
          confirmButtonText: '确定'
        })
        this.sum = this.updateData.sum
        return
      }
      if (this.tableData.length && a != this.tableData[0].sum && !this.lockNo) {
        this.lockNo = true
      }
      this.updateData.sum = a
      this.updateData.updateNumber = a - this.updateData.initialSum
      this.updateData.money = (this.updateData.onePrice * this.updateData.sum).toFixed(2)
      this.updateData.updateMoney = (this.updateData.money - this.updateData.initialMoney).toFixed(2)
    },

    customerChange(e){
      this.customerNo = e
      if (this.tableData.length && this.customerNo != this.tableData[0].no) {
        this.changeNo = true
        for (const i of this.customerL) {
          if (i.value == this.customerNo) {
            this.checkDate()
            this.tableData.forEach(e => {
              e.no = this.customerNo
              e.name = i.label
            })
            return
          }
        }
      }
    },

    itemDiscount(row){
      if (!this.lockNo) this.lockNo = true
      row.onePrice = (row.sellingPrice * row.discount / 10).toFixed(2)
      row.money = (row.onePrice * row.sum).toFixed(2)
      row.updateMoney = (row.money - row.initialMoney).toFixed(2)
    },

    fillBlanks(row){
      console.log(row)
      this.updateData = row
      
      this.receiptsNumber = row.receiptsNumber
      this.kindsNumber = row.kindsNumber
      this.inputDate = row.sellTime
      this.customerNo = row.no
      this.customerName = row.name
      this.sequence = row.sequence
      this.cooperateWay = row.cooperateWay
      this.remark = row.remark
      this.sellingPrice = row.sellingPrice

      // this.customerNoBlur()
      this.checkDate()
    },
    rowClick(row){
      // console.log(row)
      this.checked2 = row.isReturn ? true : false
      this.sum = row.sum
      this.discount = row.discount
      this.actualPrice = row.onePrice
      this.updateData = row
      this.checked3 = row.isOfficialReceipts ? true : false
    },

    // 查询
    search(){
      this.clearData()
      if (!this.searchInputSequence && !this.searchKindsNumber) {
        this.$alert('请输入查询条件', '', {
          confirmButtonText: '确定'
        })
        return
      }
      this.tableData = []
      if (this.searchKindsNumber) {
        updateReceipt({
          sellSequence: this.searchInputSequence,
          kindsNumber: this.searchKindsNumber
        }).then(res => {
          if (res.data.data) {
            this.tableData = res.data.data
            this.tableData.forEach(e => {
              e.colorNameNo = e.colorName + ' ' + e.size
              e.time = e.sellTime.slice(0,10)
              e.oldNo = e.no
              e.initialSum = e.sum
              e.initialMoney = e.money
              // 是否实价 0否1是
              e.isOfficialReceipts = 0
              // e.sellTime += ' 12:00:00'
            })
            this.fillBlanks(this.tableData[0])
            this.isAffirm = this.tableData[0].affirm ? true : false
            if (this.lockNo) this.lockNo = false
            if (this.changeNo) this.changeNo = false
          }
        })
      } else {
        getSellInquire({
          sellSequence: this.searchInputSequence,
          limit: 99999,
          page: 1}).then(res => {
          if (res.data.data) {
            this.tableData = res.data.data.sellInquireInfoList
            this.tableData.forEach(e => {
              e.colorNameNo = e.colorName + ' ' + e.size
              e.time = e.sellTime.slice(0,10)
              e.oldNo = e.no
              e.initialSum = e.sum
              e.initialMoney = e.money
              // 是否实价 0否1是
              e.isOfficialReceipts = 0
              // e.sellTime += ' 12:00:00'
            })
            this.fillBlanks(this.tableData[0])
            this.isAffirm = this.tableData[0].affirm ? true : false
            if (this.lockNo) this.lockNo = false
            if (this.changeNo) this.changeNo = false
          }
        })
        settleAccountsStatus({sequence: this.searchInputSequence}).then(res => {
          this.settleAccount = res.data.data
        })
      }
    },
    
    modification(){
      if (this.judgeTime(this.inputDate.slice(0,10),this.maxSellDate)) {
        this.$message.info('时间不合法，不能早于' + this.maxSellDate)
        return
      }
      this.tableData.forEach(e => {
        // e.sellTime = e.sellTime.slice()
        e.flagToken = this.Str
      });
      console.log(this.isAffirm)
      console.log(this.tableData)
      if (this.isAffirm) {
        updateByAffirm(JSON.stringify(this.tableData)).then(res => {
          if (res.data.code == 200) {
            this.$message({message: `修改成功,单号:${this.receiptsNumber}需重新结账 在直营店销售查询页面重新结账`,type: 'success',duration:5000})
            this.searchInputSequence = this.sequence
            this.$emit('modifySuc')
            if (this.settleAccount) {
              // this.$router.push({path:'/stores/store_sales_query',query:{sequence:this.receiptsNumber}})
              this.$message.info(`单号:${this.receiptsNumber}请前往店铺销售查询页面查看`)
            }
            this.search()
          } else {
            this.$message.error('修改失败')
          }
        })
      } else {
        affirmUpdateReceipt(JSON.stringify(this.tableData)).then(res => {
          if (res.data.code == 200) {
            this.$message({message: '修改成功',type: 'success',duration:5000})
            this.searchInputSequence = this.sequence
            this.search()
            this.$emit('modifySuc')
          } else {
            this.$message.error('修改失败')
          }
        })
      }
    }
  }
}
</script>